<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ include file="../../../../common/common.jsp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link href="${ctx}/static/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
    <link href="${ctx}/static/css/basic.css" rel="stylesheet" type="text/css">
    <link href="${ctx}/static/plugins/validationEngine/css/validationEngine.jquery.css" rel="stylesheet"
          type="text/css">
    <style type="text/css">
        .btn-sm {
            border-width: 4px;
            font-size: 13px;
            padding: 4px 9px;
            line-height: 1.39;
        }

        .code_space {
            margin-left: -4px;
            margin-right: 14px;
        }

        .btn_key {
            background-color: #6fb3e0 !important;
            border-color: #6fb3e0;
        }

        .btn_key:hover {
            color: #fff;
            background-color: #39b3d7;
            border-color: #269abc;
        }

        .code_width {
            width: 36.5%;
        }

        @media only screen and (max-width: 767px ) {
            .code_width {
                width: 102%;
            }
        }

        .radios {
            margin-bottom: 20px;
            float: left;
            margin-left: 40px;

        }
        .image-control{
            width: 200px;
            height: 100px;
            border: solid thin seashell;
            background-color: gainsboro;
        }
        .col-sm-area{
            width: 50%;
        }
    </style>
</head>
<body>
<div class="content">

    <form method="post" id="uploadForm1" enctype="multipart/form-data">
        <input style="width:0px;height:0px; border:none; float:left; margin-left:100px; margin-top:-30px;" type="file"
               id="businessFile" name="urlfile"
               onchange="doUpload('businessFile','uploadForm1','business_img','businesslicenseImage')"/>
        <input style="width:0px;height:0px; border:none; float:left; margin-left:100px; margin-top:-30px;"
               name="type" value="1"/>
        <input style="width:0px;height:0px; border:none; float:left; margin-left:100px; margin-top:-30px;"
               name="module" value="recommend"/>
    </form>
    <form method="post" id="uploadForm2" enctype="multipart/form-data">
        <input style="width:0px;height:0px; border:none; float:left; margin-left:100px; margin-top:-30px;" type="file"
               id="idCardFile1" name="urlfile"
               onchange="doUpload('idCardFile1','uploadForm2','idCard_img1','idCardImage1')"/>
        <input style="width:0px;height:0px; border:none; float:left; margin-left:100px; margin-top:-30px;"
               name="type" value="1"/>
        <input style="width:0px;height:0px; border:none; float:left; margin-left:100px; margin-top:-30px;"
               name="module" value="recommend"/>
    </form>
    <form method="post" id="uploadForm3" enctype="multipart/form-data">
        <input style="width:0px;height:0px; border:none; float:left; margin-left:100px; margin-top:-30px;" type="file"
               id="idCardFile2" name="urlfile"
               onchange="doUpload('idCardFile2','uploadForm3','idCard_img2','idCardImage2')"/>
        <input style="width:0px;height:0px; border:none; float:left; margin-left:100px; margin-top:-30px;"
               name="type" value="1"/>
        <input style="width:0px;height:0px; border:none; float:left; margin-left:100px; margin-top:-30px;"
               name="module" value="recommend"/>
    </form>

    <form class="form-horizontal" id="addForm">
        <br>
        <br>
        <br>
        <input type="hidden" name="id" value="${agent.id}">
        <input type="hidden" name="positionId" value="${agent.positionId}">
        <div class="form-group">
            <label for="agentLevelId" class="col-sm-4 control-label"><span style="color:red;">*</span>代理级别:</label>
            <div class="col-sm-3">
                <select class="form-control validate[required]" id="agentLevelId" disabled="disabled"  name="agentLevelId"
                        onchange="setCommunity()"> </select>
                <input type="hidden" id="levelName" value="${agent.agentLevelId}">
            </div>
        </div>
        <div class="form-group">
            <label for="agentName" class="col-sm-4 control-label"><span style="color:red;">*</span>代理商名称:</label>
            <div class="col-sm-3">
                <input type="text" class="form-control validate[required]" id="agentName" name="agentName" value="${agent.agentName}" placeholder="请输入代理商名称">
            </div>
        </div>
        <div class="form-group">
            <label for="personName" class="col-sm-4 control-label"><span style="color:red;">*</span>联系人:</label>
            <div class="col-sm-3">
                <input type="text" class="form-control validate[required]" id="personName" name="personName" value="${agent.personName}" placeholder="请输入联系人">
            </div>
        </div>
        <div class="form-group">
            <label for="personTel" class="col-sm-4 control-label"><span style="color:red;">*</span>联系电话:</label>
            <div class="col-sm-3">
                <input type="text" class="form-control" id="personTel" name="personTel"
                       readonly="readonly" value="${agent.personTel}" data-fun="dataFunDemo" placeholder="不可修改">
            </div>
        </div>
        <div class="form-group">
            <label for="promoterTel" class="col-sm-4 control-label">推广师电话:</label>
            <div class="col-sm-3">
                <input type="text" class="form-control validate[custom[phone]]" value="${agent.promoterTel}" id="promoterTel" name="promoterTel" onblur="setPromoterName()"
                       data-fun="dataFunDemo" placeholder="请输入推广师电话">
            </div>
        </div>
        <div class="form-group">
            <label for="promoterName" class="col-sm-4 control-label">推广师姓名:</label>
            <div class="col-sm-3">
                <input type="text" class="form-control" id="promoterName" name="promoterName"
                       readonly="readonly" value="${agent.promoterName}" data-fun="dataFunDemo"
                       placeholder="由推广师电话自动获取">
            </div>
        </div>
        <div class="form-group">
            <label for="area_div" class="col-sm-4 control-label"><span style="color:red;">*</span>所属区域:</label>
            <div id="area_div"  style="width: 600px;height:27px;display:inline"></div>
        </div>

        <%-- <div class="form-group" id="communityIsAble">
             <label for="communityId" class="col-sm-4 control-label"><span style="color:red;">*</span>所属社区:</label>
             <div class="col-sm-3">
                 <select class="form-control validate[required]" id="communityId" name="communityId"
                         data-fun="dataFunDemo">
                     <option value='0'>请选择社区</option>
                 </select>
             </div>
         </div>--%>

        <div class="form-group">
            <label for="address" class="col-sm-4 control-label"><span style="color:red;">*</span>详细地址:</label>
            <div class="col-sm-3">
                <input type="text" class="form-control validate[required]" id="address" name="address" value="${agent.address}" data-fun="dataFunDemo" placeholder="请输入详细地址">
            </div>
        </div>
        <div class="form-group">
            <label for="businessNumber" class="col-sm-4 control-label"><span style="color:red;">*</span>营业执照:</label>
            <div class="col-sm-3">
                <input type="text" class="form-control validate[required]" id="businessNumber" name="businessNumber"
                       value="${agent.businessNumber}" data-fun="dataFunDemo" placeholder="请输入营业执照编号">
            </div>
            <div style="clear: both"></div>
            <div style="clear: both;width: 500px;margin-left: 410px;margin-top: 10px">
                <p>请上传代表营业执照的照片，照片大小不超过5M，推荐尺寸：100pxX200px。</p>


                <div id="business_img" class="image-control"
                     style="background-image: url('${agent.businessImage[0].url}');background-size: 100% 100%;">
                    <input type="hidden" name="businesslicenseImage" id="businesslicenseImage"
                           value="${agent.businessImage[0].url}"/>
                </div>
                <div style="text-align: left">
                    <input type="button" class="btn btn-success" onclick='$("#businessFile").click()' value="上传图片"/>
                </div>
            </div>

        </div>
        <div class="form-group">
            <label for="personIdCard" class="col-sm-4 control-label"><span style="color:red;">*</span>负责人身份证:</label>
            <div class="col-sm-3">
                <input type="text" class="form-control validate[required,custom[IDCard]]" id="personIdCard" name="personIdCard"
                       value="${agent.personIdCard}" data-fun="dataFunDemo" placeholder="请输入负责人身份证号">

            </div>
            <div style="clear: both"></div>
            <div style="clear: both;width: 500px;margin-left: 410px;margin-top: 10px">
                <p>请上传代表您身份的照片，照片大小不超过5M，推荐尺寸：100pxX200px。</p>

                <div style="float: left">
                    <div id="idCard_img1" class="image-control"
                         style="background-image: url('${agent.idCardsImage[0].url}');background-size: 100% 100%;">
                        <input type="hidden" name="idCardImage1" id="idCardImage1"
                               value="${agent.idCardsImage[0].url}"/>
                    </div>
                    <div style="text-align: left">
                        <input type="button" class="btn btn-success" onclick='$("#idCardFile1").click()' value="上传图片"/>
                    </div>
                </div>

                <div  style="float: left;margin-left: 10px">
                    <div id="idCard_img2" class="image-control"
                         style="background-image: url('${agent.idCardsImage[1].url}');background-size: 100% 100%;">
                        <input type="hidden" name="idCardImage2" id="idCardImage2"
                               value="${agent.idCardsImage[1].url}"/>
                    </div>
                    <div style="text-align: left">
                        <input type="button" class="btn btn-success" onclick='$("#idCardFile2").click()' value="上传图片"/>
                    </div>
                </div>

            </div>
        </div>
        <div class="form-group">
            <div class="col-sm-10 text-center">
                <button type="button" id="addBtn" class="btn btn-primary">保存</button>
            </div>
        </div>
    </form>
</div>
<script src="${ctx}/static/plugins/jQuery/jQuery-2.1.4.min.js"></script>
<script src="${ctx}/static/bootstrap/js/bootstrap.min.js"></script>
<script src="${ctx}/static/plugins/layer/layer.js"></script>
<script src="${ctx}/static/plugins/validationEngine/jquery.validationEngine-zh_CN.js"></script>
<script src="${ctx}/static/plugins/validationEngine/jquery.validationEngine.js"></script>
<script src="${ctx}/static/js/common/base.js" type="text/javascript"></script>
<script src="${ctx}/static/js/common/page.js" type="text/javascript"></script>
<script src="${ctx}/static/js/common/common.js" type="text/javascript"></script>
<script src="${ctx}/static/js/common/area.js" type="text/javascript"></script>
<script>


    //提交数据
    $.ajax({
        async       : false,
        type 		: "GET",
        url: "${ctx}/api/agentLevel/list",
        success 	: function( d ) {
            console.log(d);
            if(d.code=="200"){
                if(d!=null){
                    generateSelect("agentLevelId",d);
                }
            } else {
                alert(d.message);
            }
        }
    });

    function generateSelect(id,result) {
        var option ="<option value='{id}'>{levelName}</option>";
        var optionSelected ="<option value='{id}' selected = 'selected'>{levelName}</option>";
        var options = "";
        $(result.data).each(function (i,data) {
            if ($("#levelName").val() != null) {
                if (data.id == $("#levelName").val()) {
                    options +=  adapterStringlHandler(optionSelected, data);
                }else {
                    options +=  adapterStringlHandler(option, data);
                }
            }else{
                options +=  adapterStringlHandler(option, data);
            }

        });

        $("#"+id).html("<option value=0>请选择级别</option>"+options);

    }

    $(function () {
        
    	$("#addForm").validationEngine({ 
    		promptPosition: "topRight", 
    		validationEventTriggers:"keyup blur", 
    		success :  false,
    		failure : function() { callFailFunction()  }
   		});
    	
    	$("#addBtn").click(function(){
        	
        	//将代理等级disaled属性去掉，不然获取不到值
            $("#agentLevelId").removeAttr("disabled");
            $("select[name='provinceId']").removeAttr("disabled");
            $("select[name='cityId']").removeAttr("disabled");
            $("select[name='countyId']").removeAttr("disabled");
            $("select[name='townId']").removeAttr("disabled");
            var flag = $("#addForm").validationEngine("validate");
            if(!flag){
                return false;
            }

        	if($("#businesslicenseImage").val()==""){
             	alert("请上传营业执照照片!");
             	return;
             }
             if($("#idCardImage1").val()==""){
             	alert("请上传身份证照片!");
             	return;
             }
             if($("#idCardImage2").val()==""){
             	alert("请上传身份证照片!");
             	return;
             }
             
            //提交数据
            $.ajax({
                async       : false,
                type 		: "POST",
                url: "${ctx}/api/agent/update",
                data 		: $("#addForm").serialize(),
                success 	: function( d ) {
                    console.log(d);
                    if(d.code=="200"){
                        alert("修改成功");
                        window.location.href = "${ctx}/api/agent/listPage"
                    } else {
                        alert(d.message);
                    }
                }
            });
        });
    });

    var data = {
        provinceId:${agent.provinceId},
        cityId:${agent.cityId},
        countyId: ${agent.countyId},
        townId:${agent.townId},
    };


    areaAll({
        url: "/api/merchant/getAllPosition",
        startFun: function () {
            $("#area_div").find(".formError").remove();
        },
        totalSelect: 4,
        DivId: "area_div",
        selectWidthArr: ["90px", "90px", "90px", "90px"],
        areaArr: ["省份:", "市:", "区县:", "社区:"],
        idArr: ["provinceId", "cityId", "countyId", "townId"],
        isNeedName: false,
        spaceArrLeft: [5, 5, 5, 5],
        spaceArrRight: [5, 5, 5, 5],
        data: data,
        backFun: function () {
            $("select[name='provinceId']").addClass("form-control validate[required]");
            $("select[name='cityId']").addClass("form-control validate[required]");
            $("select[name='countyId']").addClass("form-control validate[required]");
            $("select[name='provinceId']").attr("disabled", "disabled");
            $("select[name='cityId']").attr("disabled", "disabled");
            $("select[name='countyId']").attr("disabled", "disabled");
            $("select[name='townId']").attr("disabled", "disabled");

        }
    })

    <%--areaAll({--%>
    <%--url: "/api/merchant/getAllPosition",--%>
    <%--startFun:function(){--%>
    <%--$("#area_div").find(".formError").remove();--%>
    <%--},--%>
    <%--totalSelect:3,--%>
    <%--DivId: "area_div",--%>
    <%--selectWidthArr: ["110px", "110px", "110px"],--%>
    <%--nameArr: ["provinceId", "cityId", "countyId"],--%>
    <%--areaArr: ["省份:","市:", "区县:"],--%>
    <%--idArr: ["provinceId", "cityId", "countyId"],--%>
    <%--isNeedName: false,--%>
    <%--spaceArrLeft: [5, 5, 5],--%>
    <%--spaceArrRight: [5, 5, 5],--%>
    <%--data: data,--%>
    <%--backFun: function () {--%>
    <%--$("select[name='provinceId']").addClass("form-control validate[required]");--%>
    <%--$("select[name='cityId']").addClass("form-control validate[required]");--%>
    <%--$("select[name='countyId']").addClass("form-control validate[required]");--%>
    <%--$("select[name='provinceId']").attr("disabled","disabled"); --%>
    <%--$("select[name='cityId']").attr("disabled","disabled");--%>
    <%--$("select[name='countyId']").attr("disabled", "disabled");--%>

    <%--$.ajax({--%>
    <%--url: "/api/merchant/getCommunityByCountyId",--%>
    <%--data: data,--%>
    <%--type: "post",--%>
    <%--dataType: "json",--%>
    <%--success: function (result) {--%>
    <%--var communityId = $("#communityId");--%>
    <%--var innerHtml = "<option value=''>请选择</option>";--%>
    <%--if (result.code == 200) {--%>
    <%--$(result.data).each(function (i, record) {--%>
    <%--innerHtml += "<option value=" + record.id + " " + (${agent.communityId} == record.id ? 'selected=selected' : ''--%>
    <%--)--%>
    <%--+">" + record.name + "</option>";--%>
    <%--});--%>
    <%--}--%>
    <%--communityId.html(innerHtml);--%>
    <%--}--%>
    <%--})--%>

    <%--}--%>
    <%--});--%>

    //根据所选代理级别来判断社区Item的显示与隐藏
    $("#communityIsAble").hide();
    if ((${agent.agentLevelId}) == 3) {
        $("#communityIsAble").show();
    }
    function setCommunity() {
        var id = $("#agentLevelId").val();
        if (3 == id) {
            $("#communityIsAble").show();
        } else {
            $("#communityIsAble").hide();
        }

    }


    <!--获取所有的社区 直辖市-->
    $("select[name='cityId']").change(function () {
        $.ajax({
            timeout: 3000,
            async: false,
            type: "POST",
            url: "/api/merchant/getCommunityByCountyId",
            dataType: "json",
            data: {
                'provinceId': $("select[name='provinceId']").val(),
                'cityId': $("select[name='cityId']").val(),//直辖市只能到这
            },
            success: function (data) {
                $("#communityId").empty();
                for (var i = 0; i < data.length; i++) {
                    $("#communityId").append("<option value=" + (data.data)[i].id + ">" + data[i].name + "</option>");
                }
            }
        });
    });
    <!--获取所有的社区 普通省-->
    $("select[name='countyId']").change(function () {
        $.ajax({
            timeout: 3000,
            async: false,
            type: "POST",
            url: "/api/merchant/getCommunityByCountyId",
            dataType: "json",
            data: {
                'provinceId': $("select[name='provinceId']").val(),
                'countyId': $("select[name='countyId']").val(),//省下面的县
            },
            success: function (data) {
                $("#communityId").empty();
                for (var i = 0; i < (data.data).length; i++) {
                    $("#communityId").append("<option value=" + (data.data)[i].id + ">" + (data.data)[i].name + "</option>");
                }
            }
        });
    });

    function doUpload(id, form, img, url) {
        var shang = $("#sc");
        if (shang) {
            shang.remove();
        }

        var file = $("#" + id).val();
        ;
        if (checkImgType(file)) {
            $("#" + img).append(" <div style='text-align: center;color: white;background-color: silver;opacity:0.5' id='sc'> 上传中...</div>");
            var formData = new FormData($("#" + form)[0]);

            $.ajax({
                url: '${ctx}/api/attachment/upload', /*这是处理文件上传的servlet*/
                type: 'POST',
                data: formData,
                async: true,
                cache: false,
                contentType: false,
                processData: false,
                dataType: "json",
                success: function (d) {
                    console.info(d);
                    if (d.code == "200") {
                        $("#" + url).val(d.data);
                        $("#" + img).css({
                            "background-image": "url('" + d.data + "')",
                            "height": "100px",
                            "background-size": "100% 100%"
                        });
                        $("#" + img).css({"height": "100px"});
                        $("#" + id).val(null);
                        $("#sc").remove();
//                    $("#sc").css({
//                        "background-color": "lawngreen",
//                    });
//                    $("#sc").html("上传成功");

                    } else {
                        alert(d.message);
                    }
                },
                error: function (d) {
                    alert("失败");
                    $("#sc").css({
                        "background-color": "red",
                    });
                    $("#sc").html("上传失败");
                }
            });
        }

    }

    function setPromoterName() {
        var tel = $("#promoterTel").val();
        if(tel!=""){
	        $.ajax({
	            async: false,
	            url: "/api/agent/getPromoterByTel",
	            data: {promoterTel: tel},
	            type: "GET",
	            dataType: "json",
	            success: function (d) {
	                if (d.code == "200") {
	                    $("#promoterName").val(d.data.memberName);
	                }else if (d.code == "20007") {
	                    alert(d.message);
	                    $("#promoterName").val(null);
                        $("#promoterTel").val(null);
	                }else if (d.code == "50017") {
	                    alert(d.message);
	                    $("#promoterName").val(null);
                        $("#promoterTel").val(null);
	                }
	            }
	        });
        }
    }


    /*
     * 判断图片类型
     *
     * @param ths
     *          type="file"的javascript对象
     * @return true-符合要求,false-不符合
     */
    function checkImgType(file) {
        if (file == null || file == "") {
            //alert("请选择要上传的图片!");
            return false;
        }
        if (file.lastIndexOf('.') == -1) {    //如果不存在"."
            alert("路径不正确!");
            return false;
        }
        var AllImgExt = ".jpg|.jpeg|.gif|.bmp|.png|";
        var extName = file.substring(file.lastIndexOf(".")).toLowerCase();//（把路径中的所有字母全部转换为小写）
        if (AllImgExt.indexOf(extName + "|") == -1) {
            ErrMsg = "该文件类型不允许上传。请上传 " + AllImgExt + " 类型的文件，当前文件类型为" + extName;
            alert(ErrMsg);
            return false;
        }
        return true;
    }



</script>
</body>
</html>